package com.uduemc.biso.node.web.component.html;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import com.uduemc.biso.node.core.common.entities.SiteComponent;
import com.uduemc.biso.node.core.common.udinpojo.ComponentTitleData;
import com.uduemc.biso.node.core.utils.ComponentUtil;
import com.uduemc.biso.node.web.component.html.inter.HIComponentUdin;

@Component
public class HComponentTitleUdin implements HIComponentUdin {

	private static String name = "component_title";

	@Autowired
	private BasicUdin basicUdin;

	@Override
	public StringBuilder html(SiteComponent siteComponent) {
		StringBuilder stringBuilder = new StringBuilder();
		String config = siteComponent.getComponent().getConfig();
		ComponentTitleData componentTitleData = ComponentUtil.getConfig(config, ComponentTitleData.class);
		if (componentTitleData == null || StringUtils.isEmpty(componentTitleData.getTheme())) {
			return stringBuilder;
		}
		String id = "title-id-"
				+ DigestUtils.md5DigestAsHex(String.valueOf(siteComponent.getComponent().getId()).getBytes());

		String maintitleStyle = componentTitleData.getMaintitleStyle();
		String subtagStyle = componentTitleData.getSubtagStyle();

		String maintitleHtml = componentTitleData.getMaintitleHtml();
		String subtitleHtml = componentTitleData.getSubtitleHtml();

		String maintitleHtmlTag = componentTitleData.getMaintitleHtmlTag();
		String subtitleHtmlTag = componentTitleData.getSubtitleHtmlTag();

		String aHtml = componentTitleData.getAHtml();
		String aTagAttr = componentTitleData.getATagAttr();

		Map<String, Object> mapData = new HashMap<>();
		mapData.put("comid", siteComponent.getComponent().getId());
		mapData.put("id", id);
		mapData.put("maintitleStyle", maintitleStyle);
		mapData.put("subtagStyle", subtagStyle);
		mapData.put("maintitleHtml", maintitleHtml);
		mapData.put("subtitleHtml", subtitleHtml);
		mapData.put("maintitleHtmlTag", maintitleHtmlTag);
		mapData.put("subtitleHtmlTag", subtitleHtmlTag);
		mapData.put("aHtml", aHtml);
		mapData.put("aTagAttr", aTagAttr);

		StringWriter render = basicUdin.render(name, "title_" + componentTitleData.getTheme(), mapData);
		stringBuilder.append(render);
		return stringBuilder;
	}

}
